<template>
  <basic-container>
    <avue-crud :option="option"
               :data="data"
               ref="crud"
               v-model="ruleForm"
               :page="page"
               class="policy-list"
               :before-open="beforeOpen"
               @search-change="searchChange"
               @search-reset="searchReset"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
        <!--<el-button type="text"-->
                   <!--icon="el-icon-view"-->
                   <!--size="small"-->
                   <!--@click="policyView(scope.row, scope.index)"-->
                   <!--v-if="!scope.row.collectTenant  && $store.getters.userInfo.tenantId">查看-->
        <!--</el-button>-->
        <el-button type="text"
                   icon="el-icon-delete"
                   size="small"
                   @click="policyRemove(scope.row, scope.index)"
                   v-if="scope.row.basicState && scope.row.basicState !== '1'">删除
        </el-button>
        <el-button type="text"
                   icon="el-icon-s-fold"
                   size="small"
                   @click="policyBack(scope.row, scope.index)"
                   v-if="scope.row.basicState && scope.row.basicState !== '0'">撤回
        </el-button>
        <el-button type="text"
                   icon="el-icon-edit"
                   size="small"
                   @click="policyEdit(scope.row, scope.index)">审核
        </el-button>
      </template>
      <!-- 链接的自定义列 -->
      <template slot="basicSourceUrlForm" slot-scope="scope">
        <a style="color:blue" :href="scope.row.basicSourceUrl" target="_blank">{{scope.row.basicSourceUrl}}</a>
      </template>
      <!-- 自定义表单 富文本框 -->
      <template slot-scope="scope" slot="contentHtmlForm">
        <avue-ueditor v-model="scope.row.contentHtml" :disabled="editVisible"></avue-ueditor>
      </template>
      <!-- 表单自定义按钮 -->
      <template slot-scope="scope" slot="menuForm">
        <el-button type="primary" size="small" icon="el-icon-lock" @click="handleLock" v-if="lockVisible">正文锁定</el-button>
        <el-button type="primary" size="small" icon="el-icon-edit" @click="handleEdit" v-if="editVisible">正文编辑</el-button>
        <el-button type="primary" size="small" icon="el-icon-s-fold" @click="handleBack" v-if="ruleForm.basicState && ruleForm.basicState !== '0'">撤回</el-button>
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handleSave">保存</el-button>
        <el-button type="primary" size="small" icon="el-icon-video-pause" @click.stop="handleSuspend">暂不处理</el-button>
        <el-button type="primary" size="small" icon="el-icon-check" @click.stop="handleSubmit">审核并发布</el-button>
        <el-button type="default" size="small" icon="el-icon-circle-close" @click="handleClose">取消</el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>
<script>
  import { getList, back, remove, detail, save, confirm } from "@/api/policy/review";
  import { regionTree } from "@/api/organ/region";
  import { dictTreeByCode } from "@/api/system/dict";

  const DIC = {
    STATUS: [{
      label: '待审核',
      value: '1'
    }, {
      label: '已审核',
      value: '2'
    }, {
      label: '暂不处理',
      value: '3'
    }],
    STATE: [{
      label: '已发布',
      value: '1'
    }, {
      label: '未发布',
      value: '0'
    }],
    LEVEL: [{
      label: '本级',
      value: '0'
    }, {
      label: '本级及下级',
      value: '1'
    }]
  }
  export default {
    name: "policy-review",
    components: {

    },
    data() {
      const formatStatus = (row, value, label, column) => {
        if (value == '1') {
          return "待审核"
        } else if (value == '2') {
          return "已审核"
        }
        return "暂不处理"
      };
      const formatState = (row, value, label, column) => {
        if (value == '1') {
          return "已发布"
        }
        return "未发布"
      };
      return {
        lockVisible: true,
        editVisible: false,
        ruleForm: {
        },
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          tip: false,
          border: true,
          index: true,
          indexLabel: '序号',
          size: 'small',
          addBtn: false,
          editBtn: false,
          delBtn: false,
          columnBtn: false,
          refreshBtn: false,
          searchShow: false,
          updateBtn: false,
          cancelBtn: false,
          dialogClickModal: false,
          menuWidth: 140,
          column: [
            {
              label: "标题",
              prop: "basicTitle",
              search: true,
              minWidth: 200,
              searchSpan: 8,
              display: false
            },
            {
              label: "发文部门",
              prop: "basicDepartmentName",
              display: false
            },
            {
              label: "发文日期",
              prop: "basicReleaseDate",
              type: "date",
              format: "yyyy-MM-dd",
              searchSpan: 10,
              align: 'center',
              searchRange: true,
              search: true,
              display: false
            },
            {
              label: "发布状态",
              prop: "basicState",
              align: 'center',
              type: 'select',
              dicData: DIC.STATE,
              formatter: formatState,
              width: 100,
              search: true,
              display: false
            },
            {
              label: "审核状态",
              prop: "basicStatus",
              align: 'center',
              type: 'select',
              dicData: DIC.STATUS,
              formatter: formatStatus,
              width: 100,
              search: true,
              display: false
            },
            {
              label: "所属区划",
              prop: "regionCode",
              type: "tree",
              dicData: [],
              props: {
                value: 'shortCode',
                label: "title"
              },
              search: true,
              hide: true,
              display: false
            },
            {
              label: "",
              prop: "regionLevel",
              type: 'radio',
              dicData: DIC.LEVEL,
              search: true,
              searchValue: '0',
              searchSpan: 4,
              searchLabelWidth: '0',
              hide: true,
              display: false
            },
            {
              label: "关键词",
              prop: "extendKeywords",
              searchSpan: 8,
              search: true,
              hide: true,
              display: false
            },
          ],
          group: [
            {
              label: "基本信息",
              icon: 'el-icon-chat-square',
              column: [
                {
                  label: "标题",
                  prop: "basicTitle",
                  span: 24,
                  rules: [{required: true, message: "请输入标题", trigger: "blur"}]
                },
                {
                  label: "文号",
                  prop: "basicIssuedNumber",
                  span: 24
                },
                {
                  label: "原文地址",
                  prop: "basicSourceUrl",
                  formslot: true,
                  readonly: true,
                  span: 24,
                },
                {
                  label: "所属区划",
                  prop: "regionCode",
                  type: "tree",
                  dicData: [],
                  props: {
                    value: 'shortCode',
                    label: "title"
                  },
                  rules: [
                    { required: true, message: "请选择所属区划", trigger: "blur" }
                  ]
                },
                {
                  label: "发文单位",
                  prop: "basicDepartmentName",
                  rules: [
                    { required: true, message: "请输入发文单位", trigger: "blur" }
                  ]
                },
                {
                  label: "发文日期",
                  prop: "basicReleaseDate",
                  type: "date",
                  format: "yyyy-MM-dd",
                  valueFormat: "yyyy-MM-dd",
                  rules: [
                    { required: true, message: "请选择发文日期", trigger: "blur" }
                  ]
                },
                {
                  label: "收集时间",
                  prop: "collectDate",
                  type: "datetime",
                  readonly: true,
                }
              ]
            },
            {
              label: "关联信息",
              icon: 'el-icon-edit-outline',
              column: [
                {
                  label: "专题分类",
                  prop: "subjectList",
                  type: "tree",
                  multiple: true,
                  dicData: [],
                  props: {
                    value: 'id',
                    label: "title"
                  }
                },
                {
                  label: "对象分类",
                  prop: "extendCorporation",
                  type: "tree",
                  multiple: true,
                  dicData: [],
                  props: {
                    value: 'id',
                    label: "title"
                  }
                },
                {
                  label: "主题分类",
                  prop: "basicSubjectClassification",
                  type: "tree",
                  multiple: true,
                  dicData: [],
                  props: {
                    value: 'id',
                    label: "title"
                  }
                },
                // {
                //   label: "主题词",
                //   prop: "basicSubjectWords"
                // },
                {
                  label: "文件依据",
                  prop: "extendRedundantField5"
                },
                {
                  label: "关键词",
                  prop: "extendKeywords",
                  type: "textarea",
                  span: 24,
                  minRows: 3
                },
              ]
            },
            {
              label: "正文",
              icon: 'el-icon-document',
              column: [
                {
                  prop: "contentHtml",
                  formslot: true,
                  labelWidth: 0,
                  span: 24,
                }
              ]
            }
          ],
        },
        data: [],
      };
    },
    created() {
      // 获取字典、区划、部门
      regionTree().then(res => {
        const data = res.data;
        this.setRegionData("regionCode", data);
      });
      dictTreeByCode('policy_special_subject').then(res => {
        const data = res.data;
        this.setDicData("subjectList", data);
      });
      dictTreeByCode('policy_object_kind').then(res => {
        const data = res.data;
        this.setDicData("extendCorporation", data);
      });
      dictTreeByCode('policy_subject_kind').then(res => {
        const data = res.data;
        this.setDicData("basicSubjectClassification", data);
      });
    },
    methods: {
      onLoad(page, params = {}) {
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data;
          this.page.total = data.total;
          this.data = data.records;
        });
      },
      beforeOpen(done, type) {
        this.lockVisible = true;
        this.editVisible = false;
        done();
      },
      policyView(row, index) {
        detail(row)
          .then(res => {
            this.$refs.crud.rowView(res.data, index);
          })
          .catch(() => {
            this.$message.error("获取政策详情失败");
          });
      },
      policyEdit(row, index) {
        detail(row)
          .then(res => {
            this.$refs.crud.rowEdit(res.data, index);
          })
          .catch(() => {
            this.$message.error("获取政策详情失败");
          });
      },
      policyBack(row, index) {
        this.$confirm("确定要撤回该政策吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return back(row);
          })
          .then(ret => {
            if (ret.success) {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }).catch(() => {
        });
      },
      policyRemove(row, index) {
        this.$confirm("确定要删除该政策吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row);
          })
          .then(ret => {
            if (ret.success) {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }).catch(() => {
        });
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        if (params.basicReleaseDate && params.basicReleaseDate.length > 1) {
          params.startDate = params.basicReleaseDate[0];
          params.endDate = params.basicReleaseDate[1];
          delete params.basicReleaseDate;
        }
        this.query = params;
        this.onLoad(this.page, params);
        done();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },

      handleLock() {
        this.lockVisible = false;
        this.editVisible = true;
      },
      handleEdit() {
        this.lockVisible = true;
        this.editVisible = false;
      },
      handleBack() {
        this.$confirm("确定要撤回该政策吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return back({id: this.ruleForm.id});
          })
          .then(ret => {
            if (ret.success) {
              this.handleClose();
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }).catch(() => {
        });
      },
      handleSave() {
        if (!this.ruleForm.contentHtml) {
          this.$message({
            type: "error",
            message: "正文不能为空"
          });
          return;
        }
        this.$refs.crud.$refs.dialogForm.$refs.tableForm.validate(vaild=>{
          if(vaild){
            this.ruleForm.regionName = this.ruleForm.$regionCode;
            save(this.ruleForm).then(ret => {
              if (ret.success) {
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
              } else {
                this.$message({
                  type: "error",
                  message: ret.msg
                });
              }
            }, error => {
              console.log(error);
              this.handleClose();
            });
          }
        })
      },
      handleSuspend() {
        this.ruleForm.regionName = this.ruleForm.$regionCode;
        this.ruleForm.basicStatus = '3';
        save(this.ruleForm).then(ret => {
          if (ret.success) {
            this.handleClose();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            this.$message({
              type: "error",
              message: ret.msg
            });
          }
        }, error => {
          console.log(error);
          this.handleClose();
        });
      },
      handleSubmit() {
        if (!this.ruleForm.contentHtml) {
          this.$message({
            type: "error",
            message: "正文不能为空"
          });
          return;
        }
        this.$refs.crud.$refs.dialogForm.$refs.tableForm.validate(vaild=> {
          if(vaild) {
            this.ruleForm.regionName = this.ruleForm.$regionCode;
            this.ruleForm.basicStatus = '2';
            confirm(this.ruleForm).then(ret => {
              if (ret.success) {
                this.handleClose();
                this.onLoad(this.page);
                this.$message({
                  type: "success",
                  message: "操作成功!"
                });
              } else {
                this.$message({
                  type: "error",
                  message: ret.msg
                });
              }
            }, error => {
              console.log(error);
            });
          }
        })
      },
      handleClose() {
        this.$refs.crud.$refs.dialogForm.handleReset();
        this.$refs.crud.$refs.dialogForm.$refs.tableForm.hide();
      },
      // 赋值区划值
      setRegionData(key, res) {
        const index = this.$refs.crud.findColumnIndex(key);
        this.option.column[index].dicData = res;
        this.option.group[0].column.forEach((val, index) => {
          if (val.prop == key) {
            this.option.group[0].column[index].dicData = res;
          }
        });
      },
      // 赋值字典值
      setDicData(key, res) {
        this.option.group[1].column.forEach((val, index) => {
          if (val.prop == key) {
            this.option.group[1].column[index].dicData = res;
          }
        });
      },
    }
  }
</script>

<style scoped lang="scss">
  @import "~_s/placeholders";
  @import "~_s/table-list";

  ::v-deep .policy-list {
    @extend %fullsize;
    @extend %table-list;
  }

  ::v-deep .ql-editor p {
    margin-bottom: 15px;
    text-indent: 2em;
  }
  ::v-deep .avue-crud__dialog .el-dialog .el-dialog__body {
    padding: 0px 15px 0px;
  }
  ::v-deep .policy-select {
    .avue-crud__menu {
      display: none;
    }
    .avue-crud-search__menu {
      height: 32px;
    }
  }
</style>